package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author buddy
 * @date 2021/8/25
 */
public class XmlConfigBuilder {

    private Configuration configuration;


    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用 dom4j 将配置文件进行解析，封装 Configuration 的方法
     */
    public Configuration parseConfig(InputStream inputStream) {
        try {
            Document document = new SAXReader().read(inputStream);
            // <configuration>
            Element rootElement = document.getRootElement();
            List<Element> elementList = rootElement.selectNodes("//property");

            Properties properties = new Properties();
            for (Element element : elementList) {
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name,value);
            }
            // 使用 c3p0 连接池
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
            comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
            comboPooledDataSource.setUser(properties.getProperty("username"));
            comboPooledDataSource.setPassword(properties.getProperty("password"));

            configuration.setDataSource(comboPooledDataSource);

            // mapper.xml 解析
            // 1. 拿到路径
            List<Element> mapperList = rootElement.selectNodes("//mapper");
            for (Element element : mapperList) {
                String mapperPath = element.attributeValue("resource");
                // 2. 转为字节输入流
                InputStream resourceAsStream = Resources.getResourceAsStream(mapperPath);
                // 3. dom4j 解析
                XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
                xmlMapperBuilder.parse(resourceAsStream);
            }

        } catch (DocumentException | PropertyVetoException e) {
            e.printStackTrace();
        }
        return configuration;
    }
}
